package com.yh.csx.bsf.flow.web.controller.manager;

import com.fasterxml.jackson.core.type.TypeReference;
import com.yh.csx.bsf.core.base.Ref;
import com.yh.csx.bsf.core.util.JsonUtils;
import com.yh.csx.bsf.core.util.StringUtils;
import com.yh.csx.bsf.flow.core.base.FlowException;
import com.yh.csx.bsf.flow.core.base.Variable;
import com.yh.csx.bsf.flow.core.base.Xml;
import com.yh.csx.bsf.flow.core.db.DbHelper;
import com.yh.csx.bsf.flow.core.util.XmlUtil;
import com.yh.csx.bsf.flow.dao.dal.t_flow_dal;
import com.yh.csx.bsf.flow.dao.dal.t_model_dal;
import com.yh.csx.bsf.flow.dao.dal.t_task_dal;
import com.yh.csx.bsf.flow.dao.model.auto.t_model_model;
import com.yh.csx.bsf.flow.engine.state.StateEngine;
import com.yh.csx.bsf.flow.web.base.SpringMvcController;
import com.yh.csx.bsf.flow.web.base.User;
import com.yh.csx.bsf.flow.web.base.pager.Pager1;
import lombok.val;
import lombok.var;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: chejiangyi
 * @version: 2019-10-23 09:43
 **/
@Controller
@RequestMapping("/manager/flow")
public class FlowController extends SpringMvcController {
    @RequestMapping("/index")
    public ModelAndView index(Integer id, String title, String approve_node, String approve_by, String create_by, Integer flow_state,String model_name,Integer model_version,String create_time_from,String create_time_to, Integer pageindex, Integer pagesize)
    {
        val pageIndex2=(pageindex == null?1:pageindex); val pageSize2=(pagesize == null?10:pagesize);
        html.s2("id",id).s2("title",title).s2("approve_node",approve_node).s2("approve_by",approve_by).s2("create_by",create_by).s2("flow_state", flow_state==null?0:flow_state).s2("model_name",model_name).s2("model_version",model_version)
                .s2("create_time_from",create_time_from).s2("create_time_to",create_time_to)
                .s2("pageindex",pageindex).s2("pagesize",pagesize);
        return pageVisit((m)-> {
                    Ref<Integer> totalSize = new Ref<>(0);
                    val list = DbHelper.get(c->{
                        return new t_flow_dal().getPage(c,id, title,  approve_node,  approve_by, null, create_by,  flow_state, model_name, model_version,create_time_from,create_time_to,pageIndex2,pageSize2,totalSize);
                    });
                    new Pager1(pageIndex2,totalSize.getData()).setPageSize(pageSize2).out();
                    request.setAttribute("model",list);
                }
        );
    }
    @RequestMapping("/changevariable")
    public ModelAndView changevariable(Integer id) {
        html.s2("id",id);
        return pageVisit((m) -> {
            String variable_json = DbHelper.get((c) -> {
               val o= new t_flow_dal().get(c, id);
               return o.getFlow_variable_json();
            });
            List<Variable> variables =  JsonUtils.deserialize(variable_json, new TypeReference<List<Variable>>() {});
            if(variables==null || variables.size()==0){
                variables = new ArrayList<>();variables.add(new Variable("","",""));
            }
            html.s2("variables",variables);
        });
    }
    @RequestMapping("/saveVariable")
    public ModelAndView saveVariable(Integer id,String variable_json) {

        return jsonVisit((m) -> {
            Ref<String> variable_json_t = new Ref<>(variable_json);
            try {
                var json = JsonUtils.deserialize(variable_json, new TypeReference<List<Variable>>() {});
                if(json==null){
                    json = new ArrayList<>();
                }
                json = json.stream().filter(c-> !StringUtils.isEmpty(c.getKey())).collect(Collectors.toList());
                variable_json_t.setData(JsonUtils.serialize(json));
            } catch (Exception e) {
                throw new FlowException("json 格式错误", e);
            }
            DbHelper.call((c) -> {
                 new t_flow_dal().updateFlowVariable(c, id, variable_json_t.getData());
            });

            return "ok";
        });
    }
    @RequestMapping("/changenode")
    public ModelAndView changenode(Integer id) {
        html.s2("id",id);
        return pageVisit((m) -> {
            String xml = DbHelper.get((c) -> {
                val o= new t_flow_dal().get(c, id);
                val nodes = new t_model_dal().get(c,o.model_id);
                return nodes.getXml();
            });
            val nodes =  XmlUtil.deserialize(xml,Xml.class);
            html.s2("nodes",nodes.getNodes());
        });
    }
    @RequestMapping("/saveNode")
    public ModelAndView saveNode(Integer id,String node) {
        return jsonVisit((m) -> {
            new StateEngine().changeNode(id,node,User.getCurrent().getUserno(),"系统管理员切换审批节点");
            return "ok";
        });
    }
    @RequestMapping("/changemodel")
    public ModelAndView changemodel(Integer id) {
        html.s2("id",id);
        return pageVisit((m) -> {
            List<t_model_model> data = DbHelper.get((c) -> {
                val o= new t_flow_dal().get(c, id);
                html.s2("currentid",o.model_id);
                Ref<Integer> total = new Ref<>(0);
                val histroy = new t_model_dal().getHistroy(c,o.getModel_name(),0,1000,total);
                return histroy;
            });

            html.s2("models",data);
        });
    }
    //setUse
    @RequestMapping("/setUse")
    public ModelAndView setUse(Integer id,Integer modelid) {
        return jsonVisit((m) -> {
            DbHelper.call((c) -> {
               val f = new t_flow_dal().get(c,id);
               val m2 = new t_model_dal().get(c,modelid);
               new t_flow_dal().updateModel(c,f.id,m2.id,m2.name,m2.title,m2.version);
            });

            return "ok";
        });
    }

    @RequestMapping("/del")
    public ModelAndView del(Integer id) {
        return jsonVisit((m) -> {
            DbHelper.call((c) -> {
                new t_task_dal().deleteTasks(c,id);
                new t_flow_dal().delete(c,id);
            });

            return "ok";
        });
    }

    @RequestMapping("/close")
    public ModelAndView close(Integer id) {
        return jsonVisit((m) -> {
            new StateEngine().close(id, User.getCurrent().getUserno(),"系统管理员关闭流程");
            return "ok";
        });
    }

    @RequestMapping("/reflow")
    public ModelAndView reflow(Integer id) {
        return jsonVisit((m) -> {
            new StateEngine().reflow(id,User.getCurrent().getUserno(),"系统管理员重新发起流程");
            return "ok";
        });
    }
}
